import { fetchMessages } from '../../utils/request';

Page({
  data: {
    chatId: null,
    chatType: null,
    chatMessages: [],
    inputValue: '',
    toBottom: ''
  },

  onLoad(options) {
    const { itemId, chatType } = options;
    this.setData({ chatId: itemId, chatType: chatType });

    // 根据 chatType 获取不同的消息数据
    this.fetchMessages(itemId, chatType);
  },

  fetchMessages(chatId, chatType) {
    // 调用实际的API接口来获取消息数据
    // 示例数据
    let messages = [];
    if (chatType === '关注') {
      messages = [
        { id: 1, sender: '我的关注', content: '今天吧!', avatarUrl: '/images/img2.jpg' }
      ];
    } else if (chatType === '商家') {
      messages = [
        { id: 1, sender: '商家', content: '好的', avatarUrl: '/images/img3.jpg' }
      ];
    }

    this.setData({ chatMessages: messages });
    this.scrollToBottom();
  },

  handleInput(e) {
    this.setData({ inputValue: e.detail.value });
  },

  sendMessage() {
    const { chatId, inputValue, chatMessages } = this.data;
    if (!inputValue) return;

    const newMessage = {
      id: chatMessages.length + 1,
      sender: '我',
      content: inputValue,
      avatarUrl: '/path/to/my-avatar.png'
    };

    this.setData({
      chatMessages: [...chatMessages, newMessage],
      inputValue: ''
    });

    // 模拟发送消息到服务器
    setTimeout(() => {
      const replyMessage = {
        id: chatMessages.length + 2,
        sender: this.data.chatType === '关注' ? '我的关注' : '商家',
        content: '收到，我会尽快处理！',
        avatarUrl: this.data.chatType === '关注' ? '/path/to/follower-avatar.png' : '/path/to/business-avatar.png'
      };
      this.setData({
        chatMessages: [...this.data.chatMessages, replyMessage]
      });
      this.scrollToBottom();
    }, 1000);

    this.scrollToBottom();
  },

  scrollToBottom() {
    this.setData({
      toBottom: `message${this.data.chatMessages.length - 1}`
    });
  }
});